#!/bin/bash
#初始化元数据信息，将需要导入的文件的全路径保存到mysql数据库中

#异步执行sql语句
function rsync_exec_mysql(){
	`nohup exec_mysql $@ &`
}

#执行sql语句
function exec_mysql(){
	#2>>/dev/null
	sql=$@
	#echo sql: ${sql}
	V_RESULT=`mysql -s -h${V_MYSQL_HOST} -u${V_MYSQL_USER} -p${V_MYSQL_PSWD} -e "$sql" 2>>/dev/null`
	
	ret=$?
	if [[ $ret -eq 0 ]];then
		if [[ -n ${V_RESULT} ]];then
			echo ${V_RESULT}
		fi
	else
		exit 9
	fi
}

#遍历目录
function traversal(){
	#echo "dir: "$1
	dir_or_files=`ls $1`
	#echo $dir_or_files
    for element in $dir_or_files
    do  
        dir_or_file=$1/$element
        if [ -d $dir_or_file ];then 
            traversal $dir_or_file
        else
			if [[ $dir_or_file == *.txt ]];then
				echo -e "\nfile: $dir_or_file"
				proc_file $dir_or_file
			fi
        fi  
    done
}

#处理文件，插入到数据库表中
function proc_file(){
    full_file_path=$1
	table_name=`get_table_name $full_file_path`
	
	sql="INSERT INTO hive_load.load_file_infos (full_file_path, table_name, flag) VALUE ('$full_file_path', '$table_name', '');"
	exec_mysql $sql
}

#获取表名
function get_table_name(){
    full_file_path=$1
	table_name=""
	if [[ $full_file_path == */BEPSZDT0102/* ]];then
		#小额
		table_name="ods_tmp.src_pay_small_detail"
	elif [[ $full_file_path == */HVPSZDT0101/* ]];then
		#大额
		table_name="ods_tmp.src_pay_large_detail"
	elif [[ $full_file_path == */IBPSZDT0101/* ]];then
		#网银
		table_name="ods_tmp.src_ibps_detail"
	else
		echo "[-] can not found table name match this file."
		#exit 1
	fi
	echo $table_name
}

#初始化数据库表
function init_table(){
	sql="
	DROP DATABASE IF EXISTS hive_load;
	CREATE DATABASE IF NOT EXISTS hive_load /*!40100 DEFAULT CHARACTER SET utf8 */;
	USE hive_load;

	DROP TABLE IF EXISTS load_file_infos;
	CREATE TABLE IF NOT EXISTS load_file_infos (
	  id bigint(20) unsigned zerofill NOT NULL AUTO_INCREMENT,
	  full_file_path varchar(255) DEFAULT NULL,
	  table_name varchar(255) DEFAULT NULL,
	  flag varchar(255) DEFAULT NULL,
	  PRIMARY KEY (id)
	) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

	DELETE FROM load_file_infos;
	"
	exec_mysql $sql
}


